package com.coolwar.algorithm.sort;

import java.util.Arrays;

/**
 * 归并排序
 * 空间利用率更高
 * 时间复杂度：o(N*logN)
 */
public class MergeSort {

    /**
     * 非递归实现
     */
    public static void mergerSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        int n = arr.length;
        int mergeSize = 1;
        while (mergeSize < n) {
            int l = 0;
            while (l < n) {
                int m = l + mergeSize - 1;
                if (m >= n) {
                    break;
                }
                int r = Math.min(m + mergeSize, n - 1);
                merge(arr, l, m, r);
                l = r + 1;
            }
            // 防止超过范围 INTEGER取值范围
            if (mergeSize > n / 2) {
                break;
            }
            mergeSize <<= 1;
        }

    }

    private static void merge(int[] arr, int l, int m, int r) {
        int[] help = new int[r - l + 1];
        int i = 0;
        int p1 = l;
        int p2 = m + 1;
        while (p1 <= m && p2 <= r) {
            help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= m) {
            help[i++] = arr[p1++];
        }
        while (p2 <= r) {
            help[i++] = arr[p2++];
        }
        if (help.length >= 0) {
            System.arraycopy(help, 0, arr, l, help.length);
        }
    }

    public static void main(String[] args) {
        int[] arr = {4, 3, 45, 8, 6, 3, 1, 2, 9, 8};
        mergerSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
